/*
 * param.c - 参数管理
 *
 * Last modified: 2021-12-1
 *        Author: Young Rong
 */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "param.h"

#define PARAM_PATH "cm.conf"

Param syscfg;

static Param defcfg = {
		.pwr_path = "/sys/class/gpio/gpio0/value",
		.at_path = "/dev/ttyUSB1",
		.card = "usb0",
		.wwan_redial = 30,
		.ntp_srv = "cn.pool.ntp.org",
};

void loadcfg()
{
	FILE	*fp;
	size_t	len = 0;
	ssize_t	rd;
	char	*line = NULL;
	uint8_t	cnt = 0;

	fp = fopen(PARAM_PATH, "r");
	if(!fp)
		goto failed;

	
	/*	从文件流中读取一行文本 
	*	ssize_t getline(char **lineptr, size_t *n, FILE *stream);
	*	paramater1: char **lineptr (指向存储读取行的缓冲区指针的指针)
	*					NULL：自动分配足够大的内存来存储读取的行。
	*	paramater2: size_t *n (指向存储*lineptr指向的缓冲区大小的变量的指针)
	*					如果*lineptr为NULL，n应该为0。
	*	paramater3:	FILE *stream （指向文件流的指针）
	*					表示要从中读取行的文件流。
	*/
	while((rd = getline(&line, &len, fp)) != -1)
	{
		line[rd - 1] = '\0';
		switch(cnt)
		{
			case 0: strcpy(syscfg.pwr_path, line);break;
			case 1: strcpy(syscfg.at_path, line);break;
			case 2: strcpy(syscfg.card, line);break;
			case 3: syscfg.wwan_redial = atoi(line);break;
			case 4: strcpy(syscfg.ntp_srv, line);break;
		}
		cnt ++;
	}

	if(line)
		free(line);

	return;
failed:
	/* make defaults */
	memcpy(&syscfg, &defcfg, sizeof(Param));
}
